package com.flyco.modules.stm.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.modules.stm.entity.StmSkuMaterial;
import com.flyco.modules.stm.entity.StmStoreInfo;
import com.flyco.modules.stm.service.IStmSkuMaterialService;
import com.flyco.modules.stm.service.IStmStoreInfoService;
import org.apache.shiro.SecurityUtils;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.stm.entity.StmStockCheckItem;
import com.flyco.modules.stm.entity.StmStockCheck;
import com.flyco.modules.stm.vo.StmStockCheckPage;
import com.flyco.modules.stm.service.IStmStockCheckService;
import com.flyco.modules.stm.service.IStmStockCheckItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.flyco.common.aspect.annotation.AutoLog;

/**
 * @Description: 门店盘点单
 * @Author: flyco
 * @Date: 2020-12-16
 * @Version: V1.0
 */
@Api(tags = "门店盘点单")
@RestController
@RequestMapping("/f/stm/stmStockCheck")
@Slf4j
public class StmStockCheckController {
    @Autowired
    private IStmStockCheckService stmStockCheckService;
    @Autowired
    private IStmStockCheckItemService stmStockCheckItemService;
    @Autowired
    private IStmStoreInfoService stmStoreInfoService;
    @Autowired
    private IStmSkuMaterialService stmSkuMaterialService;

    /**
     * 分页列表查询
     *
     * @param stmStockCheck
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "门店盘点单-分页列表查询")
    @ApiOperation(value = "门店盘点单-分页列表查询", notes = "门店盘点单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(StmStockCheck stmStockCheck,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<StmStockCheck> queryWrapper = QueryGenerator.initQueryWrapper(stmStockCheck, req.getParameterMap());
        Page<StmStockCheck> page = new Page<StmStockCheck>(pageNo, pageSize);
        IPage<StmStockCheck> pageList = stmStockCheckService.page(page, queryWrapper);
        if (pageList.getTotal() > 0) {
            List<StmStoreInfo> storeInfos = stmStoreInfoService.list();
            Map<Long, String> storeInfoMaps = storeInfos.stream().collect(Collectors.toMap(StmStoreInfo::getStoreId, StmStoreInfo::getName, (key1, key2) -> key2));
            pageList.getRecords().forEach(replenishment -> {
                if (oConvertUtils.isNotEmpty(replenishment.getStoreId())) {
                    if (storeInfoMaps.containsKey(replenishment.getStoreId())) {
                        replenishment.setStoreId_dictText(storeInfoMaps.get(replenishment.getStoreId()));
                    } else {
                        if (Objects.equals(0L, replenishment.getStoreId())) {
                            replenishment.setStoreId_dictText("线上商城");
                        }
                    }
                }
            });
        }
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param stmStockCheckPage
     * @return
     */
    @AutoLog(value = "门店盘点单-添加")
    @ApiOperation(value = "门店盘点单-添加", notes = "门店盘点单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody StmStockCheckPage stmStockCheckPage) {
        StmStockCheck stmStockCheck = new StmStockCheck();
        BeanUtils.copyProperties(stmStockCheckPage, stmStockCheck);
        stmStockCheckService.save(stmStockCheck);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param stmStockCheckPage
     * @return
     */
    @AutoLog(value = "门店盘点单-编辑")
    @ApiOperation(value = "门店盘点单-", notes = "门店盘点单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody StmStockCheckPage stmStockCheckPage) {
        StmStockCheck stmStockCheck = new StmStockCheck();
        BeanUtils.copyProperties(stmStockCheckPage, stmStockCheck);
        stmStockCheckService.updateById(stmStockCheck);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "门店盘点单-通过id删除")
    @ApiOperation(value = "门店盘点单-通过id删除", notes = "门店盘点单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) Long id) {
        stmStockCheckService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "门店盘点单-批量删除")
    @ApiOperation(value = "门店盘点单-批量删除", notes = "门店盘点单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.stmStockCheckService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "门店盘点单-通过id查询")
    @ApiOperation(value = "门店盘点单-通过id查询", notes = "门店盘点单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) Long id) {
        StmStockCheck stmStockCheck = stmStockCheckService.getById(id);
        return Result.ok(stmStockCheck);
    }

    //===========================以下是子表信息操作相关API====================================

    /**
     * 通过主表id查询门店盘点单记录
     *
     * @param stmStockCheckItem
     * @return
     */
    @AutoLog(value = "门店盘点单记录-通过主表id查询")
    @ApiOperation(value = "门店盘点单记录-通过主表id查询", notes = "门店盘点单记录-通过主表id查询")
    @GetMapping(value = "/listStmStockCheckItemByMainId")
    public Result<?> listStmStockCheckItemByMainId(StmStockCheckItem stmStockCheckItem,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        if (stmStockCheckItem.getStockCheckId() != null) {
            QueryWrapper<StmStockCheckItem> queryWrapper = QueryGenerator.initQueryWrapper(stmStockCheckItem, req.getParameterMap());
            Page<StmStockCheckItem> page = new Page<StmStockCheckItem>(pageNo, pageSize);
            IPage<StmStockCheckItem> pageList = stmStockCheckItemService.page(page, queryWrapper);
            return Result.ok(pageList);
        } else {
            return Result.error("请选择盘点单");
        }
    }

    /**
     * 添加门店盘点单记录
     *
     * @param stmStockCheckItem
     * @return
     */
    @AutoLog(value = "门店盘点单记录-添加")
    @ApiOperation(value = "门店盘点单记录-添加", notes = "门店盘点单记录-添加")
    @PostMapping(value = "/addStmStockCheckItem")
    public Result<?> addStmStockCheckItem(@RequestBody StmStockCheckItem stmStockCheckItem) {
        stmStockCheckItemService.save(stmStockCheckItem);
        return Result.ok("添加门店盘点单记录成功！");
    }

    /**
     * 编辑门店盘点单记录
     *
     * @param stmStockCheckItem
     * @return
     */
    @AutoLog(value = "门店盘点单记录-编辑")
    @ApiOperation(value = "门店盘点单记录-编辑", notes = "门店盘点单记录-编辑")
    @PutMapping("/editStmStockCheckItem")
    public Result<?> editStmStockCheckItem(@RequestBody StmStockCheckItem stmStockCheckItem) {
        stmStockCheckItemService.updateById(stmStockCheckItem);
        return Result.ok("编辑门店盘点单记录成功！");
    }

    /**
     * 通过id删除门店盘点单记录
     *
     * @param id
     * @return
     */
    @AutoLog(value = "门店盘点单记录-通过id删除")
    @ApiOperation(value = "门店盘点单记录-通过id删除", notes = "门店盘点单记录-通过id删除")
    @DeleteMapping(value = "/deleteStmStockCheckItem")
    public Result<?> deleteStmStockCheckItem(@RequestParam(name = "id", required = true) Long id) {
        stmStockCheckItemService.removeById(id);
        return Result.ok("删除门店盘点单记录成功！");
    }

    /**
     * 批量删除门店盘点单记录
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "门店盘点单记录-批量删除")
    @ApiOperation(value = "门店盘点单记录-批量删除", notes = "门店盘点单记录-批量删除")
    @DeleteMapping(value = "/deleteBatchStmStockCheckItem")
    public Result<?> deleteBatchStmStockCheckItem(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        }
        this.stmStockCheckItemService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");

    }


    /**
     * 导出excel
     *
     * @param request
     * @param stmStockCheck
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StmStockCheck stmStockCheck) {
        // Step.1 组装查询条件
        QueryWrapper<StmStockCheck> queryWrapper = QueryGenerator.initQueryWrapper(stmStockCheck, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<StmStockCheckItem> itemLambdaQueryWrapper = new LambdaQueryWrapper<>();
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<Long> selectionList = Arrays.asList(selections.split(",")).stream().map(s -> Long.valueOf(s.toString())).collect(Collectors.toList());
            queryWrapper.in("id", selectionList);
            itemLambdaQueryWrapper.in(StmStockCheckItem::getStockCheckId,selectionList);
        } else {
            queryWrapper.in("id", 0L);
            itemLambdaQueryWrapper.in(StmStockCheckItem::getStockCheckId,0L);
        }
        //Step.2 获取导出数据

        List<StmStockCheck> stmStockCheckList = stmStockCheckService.list(queryWrapper);
        List<StmStockCheckItem> pageList = stmStockCheckItemService.list(itemLambdaQueryWrapper);

        if (oConvertUtils.isNotEmpty(pageList) && pageList.size() > 0) {
            LambdaQueryWrapper<StmSkuMaterial> materialQueryWrapper = new LambdaQueryWrapper<>();
            materialQueryWrapper.eq(StmSkuMaterial::getDelFlag,0);
            materialQueryWrapper.le(StmSkuMaterial::getStartTime,new Date());
            List<StmSkuMaterial> skuMaterials = stmSkuMaterialService.list(materialQueryWrapper);

            Map<Long, String> materialMaps = skuMaterials.stream().collect(Collectors.toMap(StmSkuMaterial::getProductId, StmSkuMaterial::getMaterialCode, (key1, key2) -> key2));
            pageList.forEach(item -> {
                if (oConvertUtils.isNotEmpty(item.getProductId())) {
                    if (materialMaps.containsKey(item.getProductId())) {
                        item.setMaterialCode(materialMaps.get(item.getProductId()));
                    }
                }
            });
        }

		String storeName = "";
		if (oConvertUtils.isNotEmpty(stmStockCheckList) && stmStockCheckList.size() > 0) {
            Set<Long> storeIds = stmStockCheckList.stream().map(r -> r.getStoreId()).collect(Collectors.toSet());
            if (Objects.equals(storeIds.size(),1)) {
                LambdaQueryWrapper<StmStoreInfo> storeQueryWrapper = new LambdaQueryWrapper<>();
                storeQueryWrapper.in(StmStoreInfo::getStoreId,storeIds);
                StmStoreInfo storeInfo = stmStoreInfoService.getOne(storeQueryWrapper,false);
                storeName = storeInfo.getName();
            }
		}

        //Step.3 调用AutoPoi导出Excel
        ModelAndView mv = new ModelAndView(new EntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "门店盘点单");
        mv.addObject(NormalExcelConstants.CLASS, StmStockCheckItem.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(storeName +"盘点数据", "导出人:" + sysUser.getRealname(), storeName +"盘点单"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<StmStockCheckPage> list = ExcelImportUtil.importExcel(file.getInputStream(), StmStockCheckPage.class, params);
                for (StmStockCheckPage page : list) {
                    StmStockCheck po = new StmStockCheck();
                    BeanUtils.copyProperties(page, po);
                    stmStockCheckService.saveMain(po, page.getStmStockCheckItemList());
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }
}
